/*
 * ProfileKeysView.java
 *
 * Created on 12 Kasım 2008 Çarşamba, 12:50
 */
package org.testis.gui.mvc.view.testdesign;

import org.testis.gui.mvc.view.*;
import org.testis.gui.mvc.controller.testdesign.ProfileKeysController;
import org.testis.gui.mvc.controller.TestDesignControllerList;
import org.testis.gui.mvc.utilities.AtofProfileKeyTableModel;
import java.awt.Frame;
import java.awt.event.WindowListener;
import java.beans.PropertyChangeEvent;
import java.util.Collections;
import java.util.List;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.SwingConstants;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author  nurhat
 */
public class ProfileKeysView extends AtofBaseDialog implements
        AbstractViewPanel {

    private static final long serialVersionUID = 9752302L;
    private TableRowSorter<TableModel> sorter;

    /** Creates new form ProfileKeysView */
    public ProfileKeysView(java.awt.Frame parent,
            boolean modal) {
        super(parent,
                modal);
        initComponents();

    }

    private void filterTable() {
        String text = txtFilter.getText();
        if (text.length() == 0) {
            sorter.setRowFilter(null);
        } else {
            sorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
        }
    }

    public ProfileKeysView(Frame parent,
            boolean modal,
            AtofProfileKeyTableModel tableModel) {
        super(parent,
                modal);
        initComponents();
        sorter = new TableRowSorter<TableModel>(tableModel);
        profileKeysTable.setRowSorter(sorter);
        profileKeysTable.setModel(tableModel);


    }

    private TableModelListener addListener() {
        return new TableModelListener() {

            public void tableChanged(
                    TableModelEvent evt) {
                try {
                    if (evt.getType() ==
                            TableModelEvent.UPDATE) {
                        int column =
                                evt.getColumn();
                        if (column > 0) {

                            int row =
                                    profileKeysTable.getSelectedRow();

                            String currentParameter =
                                    (String) profileKeysTable.getValueAt(
                                    row,
                                    0);
                            String currentValue =
                                    (String) profileKeysTable.getValueAt(
                                    row,
                                    1);
                            int id = Integer.parseInt(currentParameter);
                            String currentGroup =
                                    (String) profileKeysTable.getValueAt(row,
                                    2);
                            String currentPriority =
                                    (String) profileKeysTable.getValueAt(row,
                                    3);
                            String[] priorityList = {
                                "P1",
                                "P2",
                                "P3",
                                "P4",
                                "P5",
                                "P6",
                                "P7",
                                "P8",
                                "P9",
                                "P10"
                            };
                            String groupName =selectGroupName(currentGroup);
                            String priority =
                                    (String) JOptionPane.showInputDialog(
                                    null,
                                    "Select priority for key :" + currentValue + "?",
                                    "Day",
                                    JOptionPane.QUESTION_MESSAGE,
                                    null, // Use default icon
                                    priorityList,
                                    currentPriority);
                            if (priority != null) {
                                TestDesignControllerList.newInstance().
                                        getProfileKeysController().
                                        operationEditKey(id,
                                        currentValue, groupName.toUpperCase(), priority);
                            }
                            filterTable();
                        }


                    }
                } catch (Exception ex) {
                }
            }
        };
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnl2 = new javax.swing.JPanel();
        jLabel8 = new javax.swing.JLabel();
        txtFilter = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        profileKeysTable = new javax.swing.JTable();
        btnEdit = new javax.swing.JButton();
        btnAdd = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();
        btnExit = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Global Profile Keys");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        pnl2.setBackground(new java.awt.Color(241, 240, 235));

        jLabel8.setText("Filter:");

        txtFilter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtFilterActionPerformed(evt);
            }
        });

        profileKeysTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        profileKeysTable.setUpdateSelectionOnSort(false);
        jScrollPane1.setViewportView(profileKeysTable);

        btnEdit.setText("Edit");
        btnEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditActionPerformed(evt);
            }
        });

        btnAdd.setText("Add");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        btnDelete.setText("Delete");
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        btnExit.setText("Exit");
        btnExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExitActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnl2Layout = new javax.swing.GroupLayout(pnl2);
        pnl2.setLayout(pnl2Layout);
        pnl2Layout.setHorizontalGroup(
            pnl2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnl2Layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addComponent(jLabel8)
                .addGap(18, 18, 18)
                .addComponent(txtFilter, javax.swing.GroupLayout.DEFAULT_SIZE, 282, Short.MAX_VALUE)
                .addGap(158, 158, 158))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnl2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnEdit)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnAdd)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnDelete)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 262, Short.MAX_VALUE)
                .addComponent(btnExit)
                .addContainerGap())
            .addGroup(pnl2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 490, Short.MAX_VALUE)
                .addContainerGap())
        );
        pnl2Layout.setVerticalGroup(
            pnl2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnl2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnl2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(txtFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(pnl2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAdd)
                    .addComponent(btnDelete)
                    .addComponent(btnEdit)
                    .addComponent(btnExit))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(pnl2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(29, 29, 29))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(pnl2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
    try {
        int startingRow =
                profileKeysTable.getSelectedRow();
        if (startingRow >= 0) {
            String currentParameter =
                    (String) profileKeysTable.getValueAt(
                    startingRow,
                    0);
            String currentValue =
                    (String) profileKeysTable.getValueAt(startingRow,
                    1);
            String currentGroup =
                    (String) profileKeysTable.getValueAt(startingRow,
                    2);
            String currentPriority =
                    (String) profileKeysTable.getValueAt(startingRow,
                    3);
            int id = Integer.parseInt(currentParameter);
            String newValue = JOptionPane.showInputDialog("Enter  Key Name:",
                    currentValue);
            if (newValue != null) {
                String[] priorityList = {
                    "P1",
                    "P2",
                    "P3",
                    "P4",
                    "P5",
                    "P6",
                    "P7",
                    "P8",
                    "P9",
                    "P10"
                };
                String groupName =selectGroupName( currentGroup);
                String priority =
                        (String) JOptionPane.showInputDialog(
                        this,
                        "Select Priority For " + newValue + "?",
                        "Select Priority",
                        JOptionPane.QUESTION_MESSAGE,
                        null, // Use default icon
                        priorityList,
                        currentPriority);
                if (priority != null) {
                    TestDesignControllerList.newInstance().
                            getProfileKeysController().
                            operationEditKey(id,
                            newValue, groupName.toUpperCase(), priority);
                }
            }
            filterTable();
        }
    } catch (Exception ex) {
    }
}//GEN-LAST:event_btnEditActionPerformed
  private String selectGroupName(String value)
    {
        List<String> lst=  TestDesignControllerList.newInstance().getProfileKeysController().operationGetProfileKeysGroupNames();
        Collections.sort(lst, String.CASE_INSENSITIVE_ORDER);

        JComboBox cbmList = new JComboBox();
        cbmList.addItem("OTHER");
         final JTextField txtField = new JTextField();
        txtField.setText("");
        txtField.setSize(200, 20);
        txtField.setVisible(true);
         JPanel panel = new JPanel();
        for(int i=0;i<lst.size();i++)
        {
            cbmList.addItem(lst.get(i));
            if(!value.equals("")&&value.equals(lst.get(i)))
            {
                cbmList.setSelectedIndex(i+1);
            }
        }
       
        cbmList.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                  JComboBox cb = (JComboBox)evt.getSource();
                  System.out.println(cb.getSelectedIndex());
                  if(cb.getSelectedIndex()==0)
                  {
                      txtField.setVisible(true);
                  }
                  else
                     txtField.setVisible(false);
            }
        });
   
       
        panel.setSize(400, 400);
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(panel);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(cbmList, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(txtField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 181, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(cbmList, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

       
       
       panel.setLayout(layout);

       int result=  JOptionPane.showConfirmDialog(null, panel);
        if (result == JOptionPane.YES_OPTION) {
            if(cbmList.getSelectedIndex()>0)
              return  (String) cbmList.getSelectedItem();
            else
                return txtField.getText();
        } else {
            return value;
        }
       
    }
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
    String keyName = JOptionPane.showInputDialog("Enter Key Name:");
    if (keyName != null) {
        if (!keyName.trim().equals("")) {
            String[] priorityList = {
                "P1",
                "P2",
                "P3",
                "P4",
                "P5",
                "P6",
                "P7",
                "P8",
                "P9",
                "P10"
            };
            String groupName = selectGroupName("");
            String priority =
                    (String) JOptionPane.showInputDialog(
                    this,
                    "Select Priority For " + keyName + "?",
                    "Select Priority",
                    JOptionPane.QUESTION_MESSAGE,
                    null, // Use default icon
                    priorityList,
                    priorityList[priorityList.length - 5]);
            if (priority != null) {
                TestDesignControllerList.newInstance().getProfileKeysController().
                        operationAddKey(keyName, groupName.toUpperCase(), priority);
            }
            filterTable();
        }
    }
}//GEN-LAST:event_btnAddActionPerformed

private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
    int startingRow =
            profileKeysTable.getSelectedRow();
    if (startingRow >= 0) {
        String currentParameter =
                (String) profileKeysTable.getValueAt(
                startingRow,
                0);
        String currentValue =
                (String) profileKeysTable.getValueAt(startingRow,
                1);
        int result =
                javax.swing.JOptionPane.showConfirmDialog(null,
                "Confirmation",
                "Are you sure?",
                javax.swing.JOptionPane.YES_NO_CANCEL_OPTION,
                javax.swing.JOptionPane.QUESTION_MESSAGE);
        if (result == javax.swing.JOptionPane.YES_OPTION) {
            int id = Integer.parseInt(currentParameter);
            TestDesignControllerList.newInstance().getProfileKeysController().
                    operationRemoveKey(id);
        }
        filterTable();
    }
}//GEN-LAST:event_btnDeleteActionPerformed

private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExitActionPerformed
    this.dispose();
}//GEN-LAST:event_btnExitActionPerformed

private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
    WindowListener[] listeners = getWindowListeners();
    for (int i = 0; i < listeners.length; i++) {
        this.removeWindowListener(listeners[i]);
    }
    this.setVisible(false);
    this.setEnabled(false);
    TestDesignControllerList.newInstance().getProfileKeysController().
            operationCloseWindow();
    this.dispose();
}//GEN-LAST:event_formWindowClosed

private void txtFilterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtFilterActionPerformed
    filterTable();
}//GEN-LAST:event_txtFilterActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnAddKey;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnEdit;
    private javax.swing.JButton btnExit;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblProfileName;
    private javax.swing.JPanel pnl1;
    private javax.swing.JPanel pnl2;
    private javax.swing.JTable profileKeysTable;
    private javax.swing.JTextField txtFilter;
    private javax.swing.JTextField txtValue;
    // End of variables declaration//GEN-END:variables

    @Override
    public void modelPropertyChange(PropertyChangeEvent evt) {
        if (evt.getPropertyName().equals(
                ProfileKeysController.SHOW_VIEW)) {
            TestDesignControllerList.newInstance().getProfileKeysController().
                    operationLoadKeys();
            this.centerParent();
        } else if (evt.getPropertyName().equals(
                ProfileKeysController.SHOW_ERROR)) {
            String val = (String) evt.getNewValue();
            JOptionPane.showMessageDialog(
                    this,
                    val,
                    "Error Dialog",
                    JOptionPane.ERROR_MESSAGE);
        } else if (evt.getPropertyName().equals(
                ProfileKeysController.PARAMETER_MODEL_CHANGED)) {
            profileKeysTable.setModel((AtofProfileKeyTableModel) evt.getNewValue());
            profileKeysTable.getColumnModel().getColumn(0).setMaxWidth(20);
            profileKeysTable.repaint();
            sorter = new TableRowSorter<TableModel>((AtofProfileKeyTableModel) evt.getNewValue());
            profileKeysTable.setRowSorter(sorter);
            profileKeysTable.getModel().addTableModelListener(addListener());
        }
    }
}
 

